package arena

import (
	"errors"
	"fmt"
	log2 "github.com/name5566/leaf/log"
	"go.mongodb.org/mongo-driver/bson"
	"log"
	"math"
	"math/rand"
	"server/cfg"
	"server/game/bag"
	"server/game/bag/db"
	"server/game/card"
	"server/game/player"
	"server/util"
	"sort"
	"strings"
	"time"
)

// ArenaDef 定义竞技场相关常量
type ArenaDef struct{}

var sCount = 0

// 竞技场相关状态常量
const (
	StatusDel = iota
	StatusOK
	ArenaID = 1
)

// ArenaLogic 竞技场逻辑处理类
type ArenaLogic struct{}

// arrAtkedField 被攻击用户的相关字段
var arrAtkedField = []string{
	"uid",
	"position",
	"cur_suc",
	"history_max_suc",
	"va_opponents",
}

// arrField 竞技场用户的相关字段
var arrField = []string{
	"uid",
	"position",
	"challenge_num",
	"added_challenge_num",
	"last_challenge_time",
	"last_buy_challenge_time",
	"cur_suc",
	"history_max_suc",
	"history_min_position",
	"upgrade_continue",
	"fight_cdtime",
	"va_opponents",
}

// GetAtkedByPos 根据位置获取被攻击用户信息
func (al *ArenaLogic) GetAtkedByPos(pos int) (*Arena, error) {
	// 这里假设 ArenaDao 是一个模拟的数据库访问对象
	// 在实际应用中需要替换为真实的数据库访问逻辑
	// ArenaDao::getByPos($pos, self::$arrAtkedField) 对应以下代码
	arenaDao := NewArenaDao()
	return arenaDao.GetByPosition(pos, arrAtkedField)
}

// GetInfo 获取用户竞技场信息
func (al *ArenaLogic) GetInfo(uid string) (map[string]interface{}, error) {
	arrRet := map[string]interface{}{
		"ret": "ok",
		"res": map[string]interface{}{},
	}
	res, err := al.get(uid, arrField)
	if err != nil {
		// 从来没有进入过竞技场
		ret := al.joinArena(uid)
		if ret != "ok" {
			arrRet["ret"] = ret
			return arrRet, nil
		}
		res, err = al.get(uid, arrField)
		if err != nil {
			return nil, err
		}
	}
	oppts := al.GetOpponents(res.VaOpponents)
	if err != nil {
		return nil, fmt.Errorf("fail to get opponents in arena")
	}
	res.Opponents = oppts
	// 返回给前端发奖时间
	//res["reward_time"] = ArenaRound{}.GetRewardTime()
	//res["last_day"] = ArenaDateConfLastDays

	arrRet["res"] = res
	return arrRet, nil
}
func (al *ArenaLogic) GetMsg(uid string) []ArenaMsg {
	arenaDao := NewArenaDao()
	msg, err := arenaDao.GetMsg(uid)
	if err != nil {
		return nil
	}
	return msg
}
func (al *ArenaLogic) GetOpponents(arrOpptPos []int) []Arena {
	arenaDao := NewArenaDao()
	// 调用 ArenaDao 获取指定位置的用户信息
	arrUidPos, err := arenaDao.GetArrByPos(arrOpptPos)
	if err != nil {
		return nil
	}

	// 提取 uid 数组
	arrUid := make([]int, 0, len(arrUidPos))
	for _, item := range arrUidPos {
		arrUid = append(arrUid, item.Position)
	}

	// 获取用户信息
	arrUser, err := arenaDao.GetArrByPos(arrUid)

	// 根据 uid 对 arrUidPos 进行索引
	uidPosIndex := make(map[string]Arena)
	for _, item := range arrUidPos {
		uidPosIndex[item.UID] = item
	}

	arrRet := make([]Arena, 0, len(arrUser))
	for _, user := range arrUser {
		// 设置 position
		if posInfo, exists := uidPosIndex[user.UID]; exists {
			user.Position = posInfo.Position
		} else {
			log.Printf("No position info found for user with uid %s", user.UID)
			continue
		}
		arrRet = append(arrRet, user)
	}

	return arrRet
}

// JoinArena 用户加入竞技场
func (al *ArenaLogic) joinArena(uid string) string {
	alock := NewArenaLock(Lcck_key)
	if alock.Lock("insert") != nil {
		fmt.Printf("fail to lock t_arena for insert data")
		return "lock"
	}
	arenaDao := NewArenaDao()
	maxPosition, err := arenaDao.GetMaxPosition()
	if err != nil {
		alock.Unlock()
		log2.Error("jion err is %v", err)
		return "error"
	}
	pos := maxPosition + 1
	userInfo, _ := player.EnGetUserInfo(uid)
	opptPos, _ := al.GetOpponentPosition(pos)
	arenaInfo := Arena{
		UID:               uid,
		Position:          pos,
		VaOpponents:       opptPos,
		UserInfo:          userInfo,
		LastChallengeTime: time.Now().Unix(),
		ChallengeNum:      FREE_CHALLENGE_NUM,
		LastBuyTime:       0,
	}
	arenaDao.Insert(uid, arenaInfo)
	al.InitUserShop(uid)
	alock.Unlock()
	return "ok"
}

// get 获取用户竞技场信息
func (al *ArenaLogic) get(uid string, arrField []string) (Arena, error) {
	arenaDao := NewArenaDao()
	if arrField == nil {
		arrField = arrField
	}
	info, err := arenaDao.Get(uid)
	if err != nil {
		return Arena{}, err
	}

	// 不是同一天
	if !util.IsSameDay(info.LastChallengeTime) {
		info.ChallengeNum = 0
	}
	// 不是今天购买的补充次数需要清空
	if !util.IsSameDay(info.LastBuyTime) {
		info.LastChallengeTime = 0
		info.AddedChallengeNum = 0
	}
	return *info, nil
}

// HasReward 检查用户是否有奖励
func (al *ArenaLogic) HasReward(uid string) (bool, error) {
	arenaDao := NewArenaDao()
	info, err := arenaDao.Get(uid)
	if err != nil {
		return false, err
	}
	if info == nil {
		return false, nil
	}
	if info.VaReward == nil {
		return false, nil
	}
	return true, nil
}

// GetPositionReward 获取用户位置奖励
func (al *ArenaLogic) GetPositionReward(uid string) (map[string]interface{}, error) {
	arenaDao := NewArenaDao()
	arrRet := map[string]interface{}{
		"ret": "ok",
		"res": map[string]interface{}{},
	}
	info, err := arenaDao.Get(uid)
	if err != nil {
		fmt.Printf("fail to getPositionReward, no info in arena.")
		return nil, err
	}
	if info == nil || info.VaReward == nil {
		arrRet["ret"] = "fail"
		return arrRet, nil
	}
	err = arenaDao.UpdateReward(uid)
	if err != nil {
		arrRet["ret"] = "out_of_date"
		return arrRet, nil
	}
	// 这里假设 EnUser 是一个模拟的用户对象
	// 在实际应用中需要替换为真实的用户对象
	var chaoPiaoNum int
	bagList, err := bag.EnAddItem(uid, db.Chaopiao, chaoPiaoNum)

	arrRet["res"] = bagList
	return arrRet, nil
}

// getUserForBattle 为战斗模块构造输入数组
func (al *ArenaLogic) getUserForBattle(uid string) (map[string]interface{}, error) {
	// 将阵型ID设置为用户当前默认阵型
	cardList := card.EnGetUserAllCardNengLi(uid)
	return map[string]interface{}{
		"card_list": cardList,
	}, nil
}

// Challenge 用户挑战
// 在 ArenaLogic 结构体中添加方法
// BuyAddedChallenge 购买额外挑战次数
func (al *ArenaLogic) BuyAddedChallenge(uid string, num int) (map[string]interface{}, error) {
	var ret = make(map[string]interface{}, 0)
	araneDao := NewArenaDao()
	info, err := araneDao.Get(uid)
	if err != nil {
		return ret, err
	}

	user, err := player.EnGetUserInfo(uid)
	costGold, err := al.buyAddedChallengeInternal(*info, num, user.Vip)
	if err != nil {
		return ret, err
	}
	bagList, err := bag.EnUseItem(uid, db.Chaopiao, costGold)
	if err != nil {
		log.Printf("fail to buy added challenge, the gold is not enough")
		return ret, fmt.Errorf("fake")
	}
	log.Printf("buy info for update:%v", info)
	err = araneDao.Update(uid, bson.M{"challenge_num": info.ChallengeNum + 1})
	if err != nil {
		return ret, err
	}
	ret["bag_list"] = bagList
	return ret, nil
}

// buyAddedChallengeInternal 内部购买额外挑战次数的逻辑
func (al *ArenaLogic) buyAddedChallengeInternal(info Arena, num, vip int) (int, error) {
	//vipConfig := btstoreGet().VIP[vip]
	//arenaTimesGold, ok := vipConfig["arena_times_gold"]
	//var arenaTimesGold int
	//maxAddedNum := arenaTimesGold["num"].(int)
	//currentAddedNum := info["added_challenge_num"].(int)
	//if currentAddedNum+num > maxAddedNum {
	//	log.Printf("fail to buy added challenge, over max num if buying %d.", num)
	//	return 0, fmt.Errorf("fake")
	//}
	//
	//costGold := num * arenaTimesGold["gold"].(int)
	//info["added_challenge_num"] = currentAddedNum + num
	//info["last_buy_challenge_time"] = al.util.GetTime()
	//log.Printf("buy info for update:%v", info)
	var costGold int
	return costGold, nil
}

// GetPositionList 获取排名列表
func (al *ArenaLogic) GetPositionList(num int) ([]Arena, error) {
	var arenaList []Arena
	arenaDao := NewArenaDao()
	fields := []string{"uid", "position"}
	arrList, _ := arenaDao.GetPositionList(num, fields)

	arrUid := make([]string, 0, len(arrList))
	for _, item := range arrList {
		arrUid = append(arrUid, item.UID)
	}

	arrUserInfo, err := player.EnGetUserList(arrUid)
	if err != nil {
		return arenaList, err
	}

	for i := range arrList {
		list := &arrList[i]
		for _, userInfo := range arrUserInfo {
			if userInfo.UID == list.UID {
				list.UserInfo = userInfo
			}
		}
	}
	return arrList, nil
}
func (al *ArenaLogic) GetOpponentPosition(pos int) ([]int, error) {
	oppNum := OPPONENT_AFTER + OPPONENT_BEFOR

	// 总数
	count := al.GetCount()
	//if count < oppNum {
	//	log.Fatalf("the arena has %d npc, the number of user must be greater than %d", oppNum, oppNum)
	//	return nil, fmt.Errorf("sys err")
	//}

	if pos > count+1 {
		log2.Error("fail to get opponents position, the pos %d must be <= 1+ the total of arena %d", pos, count)
		return nil, fmt.Errorf("sys err")
	}

	var min, max int
	// 小于 100 的从前后 10 名中取
	if pos <= 100 {
		min = pos - 10
		if min <= 0 {
			min = 1
		}
		max = pos + 10
	} else if pos >= 100 { // 大于 100 的从前后 10% 里面取
		min = int(math.Floor(float64(pos) * 0.9))
		max = int(math.Floor(float64(pos) * 1.1))
	}

	// 不超过总数
	if max > count {
		max = count
	}

	// 当前位置前取 3 个
	beforNum := OPPONENT_BEFOR
	// 当前位置后取 2 个
	afterNum := OPPONENT_AFTER

	// 前段区间小于需要的数量
	if pos <= OPPONENT_BEFOR {
		beforNum = pos - 1
		afterNum = oppNum - beforNum
	}
	// 后段区间小于需要的数量
	if count-pos < afterNum {
		afterNum = count - pos
		if afterNum < 0 {
			afterNum = 0
		}
		beforNum = oppNum - afterNum
	}
	if pos <= 5 {
		beforNum = 0
		afterNum = 0
	}

	var arrRet []int
	if beforNum != 0 {
		beforArr, err := al.getRandSeq(min, pos-1, beforNum)
		if err != nil {
			log2.Error("getOpponent error")
			return nil, fmt.Errorf("sys err")
		}
		arrRet = beforArr
	}
	if afterNum != 0 {
		afterArr, err := al.getRandSeq(pos+1, max, afterNum)
		if err != nil {
			log2.Error("getOpponent error")
			return nil, fmt.Errorf("sys err")
		}
		arrRet = append(arrRet, afterArr...)
	}

	// 排序
	sort.Ints(arrRet)
	return arrRet, nil
}

// GetRandSeq 生成指定范围内不重复的随机数序列
func (al *ArenaLogic) GetRandSeq(min, max, num int) ([]int, error) {
	// 验证参数
	if min > max || num <= 0 || max-min+1 < num {
		return nil, fmt.Errorf("invalid input parameters: min=%d, max=%d, num=%d", min, max, num)
	}

	// 初始化随机数种子
	rand.Seed(time.Now().UnixNano())

	result := make([]int, 0, num)
	used := make(map[int]bool)

	for i := 0; i < num; i++ {
		x := rand.Intn(max-min+1) + min
		for used[x] {
			x++
			if x > max {
				x = min
			}
		}
		used[x] = true
		result = append(result, x)
	}

	return result, nil
}

func (al *ArenaLogic) GetCount() int {
	dao := NewArenaDao()
	sCountNum, err := dao.GetCount()
	if err != nil {
		return 0
	}
	return int(sCountNum)
}

// 示例的 getRandSeq 实现
func (al *ArenaLogic) getRandSeq(min, max, num int) ([]int, error) {
	if min > max || num <= 0 || max-min+1 < num {
		return nil, fmt.Errorf("invalid parameters")
	}

	rand.Seed(time.Now().UnixNano())
	result := make([]int, 0, num)
	used := make(map[int]bool)

	for i := 0; i < num; i++ {
		x := rand.Intn(max-min+1) + min
		for used[x] {
			x++
			if x > max {
				x = min
			}
		}
		used[x] = true
		result = append(result, x)
	}

	return result, nil
}

// GetTop 获取指定位置范围的数据
func (al *ArenaLogic) GetTop(offset, limit int, fields []string) ([]Arena, error) {
	araneDao := NewArenaDao()
	positions := make([]int, 0, limit)
	for i := offset + 1; i <= offset+limit; i++ {
		positions = append(positions, i)
	}
	return araneDao.GetArrByPos(positions)
}
func (al *ArenaLogic) FightcdtimeCost(cdtime int64) int {
	diff := cdtime - util.GetTime()
	if diff <= 0 {
		return 0
	}
	costGold := int(math.Ceil(float64(diff)/float64(CDTIME_PER_GOLD))) * 2
	return costGold
}

// Challenge 发起挑战
func (al *ArenaLogic) Challenge(uid, atkedUid string, pos, buyAddedChallengeNum int, isClearCdtime bool) (map[string]interface{}, error) {
	//if al.ArenaRound.IsLock() {
	//	log.Printf("fail to challenge in arena, the arena is lock for rewarding.")
	//	return nil, errors.New("fake")
	//}

	arrRet := map[string]interface{}{
		"ret":       "ok",
		"atk":       map[string]interface{}{},
		"cost":      0,
		"opponents": []map[string]interface{}{},
	}

	alock := NewArenaLock(Lcck_key)
	if alock.Lock(uid, atkedUid) != nil {
		arrRet["ret"] = "lock"
		return arrRet, nil
	}

	defer alock.Unlock()
	arenaDao := NewArenaDao()
	info, err := arenaDao.Get(uid)
	if err != nil {
		return nil, err
	}

	user, err := player.EnGetUserInfo(uid)
	if err != nil {
		return nil, err
	}
	//gArrReward := []int{0, 0}

	if buyAddedChallengeNum != 0 {
		costGold, err := al.buyAddedChallengeInternal(*info, buyAddedChallengeNum, user.Vip)
		_, err = bag.EnUseItem(uid, db.Chaopiao, costGold)
		if err != nil {
			log.Printf("fail to buy added challenge, the gold is not enough")
			return nil, errors.New("fake")
		}
		arrRet["cost"] = arrRet["cost"].(int) + costGold
	}

	if info.ChallengeNum <= 0 {
		if info.AddedChallengeNum <= 0 {
			log.Printf("fail to challenge, the num is not enough")
			return nil, errors.New("fake")
		}
		info.AddedChallengeNum = info.AddedChallengeNum - 1
	}

	if info.FightCdTime > time.Now().Unix() {
		if !isClearCdtime {
			log.Printf("fail to challenge in arena, the fight_cdtime isnot arrival.")
			return nil, errors.New("fake")
		}
		costGold := al.FightcdtimeCost(info.FightCdTime)
		_, err := bag.EnUseItem(uid, db.Chaopiao, costGold)
		if err != nil {
			log.Printf("fail to buy added challenge, the gold is not enough")
			return nil, errors.New("fake")
		}
		arrRet["cost"] = arrRet["cost"].(int) + costGold
	}

	found := false
	for _, oppPos := range info.VaOpponents {
		if oppPos == pos {
			found = true
			break
		}
	}
	if !found {
		log.Printf("fail to challenge in arena, the postion isnot one of opponents")
		arrRet["ret"] = "position_err"
		return arrRet, nil
	}

	atkedInfo, err := al.GetAtkedByPos(pos)
	if err != nil {
		return arrRet, nil
	}
	if atkedUid != atkedInfo.UID {
		arrRet["ret"] = "opponents_err"
		return arrRet, nil
	}

	atkedUser, err := player.EnGetUserInfo(atkedUid)
	arrMsgField := ArenaMsg{
		AttackUID:      user.UID,
		AttackName:     user.PlayerName,
		DefendUID:      atkedUser.UID,
		DefendName:     atkedUser.PlayerName,
		AttackTime:     time.Now().Unix(),
		AttackPosition: info.Position,
		DefendPosition: atkedInfo.Position,
		AttackRes:      0,
		AttackReplayID: 0,
	}

	atkRet, _, err := al.ChallengeInternal(user, atkedUser, *info, *atkedInfo)
	//arrMsgField.AttackReplayID = atkRet["server"].(map[string]interface{})["brid"]
	isSuc := atkRet["is_suc"].(bool)

	sendAtkedInfo := map[string]interface{}{
		"va_opponents": []int{},
		"position":     atkedInfo.Position,
		"arena_msg":    arrMsgField,
	}
	if isSuc {
		arrMsgField.AttackRes = 1
		sendAtkedInfo["va_opponents"] = atkedInfo.VaOpponents
		arrRet["opponents"] = al.GetOpponents(info.VaOpponents)
	}

	//addPrestige, addExperience := gArrReward[0], gArrReward[1]
	//user.AddPrestige(addPrestige)
	//user.AddExperience(addExperience)
	//user.Update()

	arrRet["atk"] = atkRet
	arrRet["experience_num"] = user.Experience
	//arrRet["prestige_num"] = user.
	arrRet["fight_cdtime"] = info.FightCdTime

	//al.ArenaAtkBroadcast(arrBroadcast, user, atkedUser)

	//arenaDao := NewArenaDao()
	err = arenaDao.InsertMsg(arrMsgField)
	if err != nil {
		return arrRet, err
	}
	arrRet["arena_msg"] = arrMsgField

	return arrRet, nil
}
func (al *ArenaLogic) ChallengeInternal(user, atkedUser player.Player, info, atkedInfo Arena) (map[string]interface{}, map[string]int, error) {
	//oldPosition := info.Position
	//oldAtkPosition := atkedInfo.Position

	// 假设 EnUser 有 PrepareItem4CurFormation 方法
	//user.PrepareItem4CurFormation()
	//atkedUser.PrepareItem4CurFormation()

	//battleUser := al.GetUserForBattle(user)
	//atkedBattleUser := al.GetUserForBattle(atkedUser)

	//bt := &Battle{}
	//options := map[string]interface{}{
	//	"bgid":    arenaConf.BATTLE_BJID,
	//	"musicId": arenaConf.BATTLE_MUSIC_ID,
	//	"type":    BattleTypeArena,
	//}
	//atkRet := bt.DoHero(battleUser, atkedBattleUser, 0, al.BattleCallback, nil, options)
	//log.Printf("Ret from battle is %v.", atkRet)

	info.FightCdTime = time.Now().Unix() + int64(FIGHT_CDTIME)
	info.ChallengeNum = info.ChallengeNum + 1
	info.LastChallengeTime = time.Now().Unix()

	diffPos := info.Position - atkedInfo.Position
	//appraisal := atkRet["server"].(map[string]interface{})["appraisal"].(string)
	//isSuc := battleDef.APPRAISAL[appraisal] <= battleDef.APPRAISAL["D"]
	arrBroadcast := make(map[string]int)
	uidCardNengLi := card.EnGetUserAllCardNengLi(user.UID)
	atkedUserNengLi := card.EnGetUserAllCardNengLi(atkedUser.UID)
	uidCardList := card.EnGetUserCardListByUid(user.UID)
	atkedUserCardList := card.EnGetUserCardListByUid(atkedUser.UID)
	uidIndex := 0
	atkIndex := 0
	b := uidIndex < len(uidCardList) && atkIndex < len(atkedUserCardList)
	var zhanBao = []BattleMsg{}
	huiHeNum := 1
	var battleMsg = BattleMsg{}
	config := cfg.ConfigData.TbHappyFightQuestion.GetDataList()
	questionMaxId := len(config)
	for b {
		wenTi := util.GetRandomInt(1, questionMaxId)
		if uidCardList[uidIndex].Charm > atkedUserCardList[atkIndex].Charm {
			battleMsg = BattleMsg{
				WenTiId:     wenTi,
				HuiHeNum:    huiHeNum,
				AktCardId:   uidCardList[uidIndex].CTId,
				AktedCardId: atkedUserCardList[atkIndex].CTId,
				IsWin:       true,
			}
		} else {
			battleMsg = BattleMsg{
				WenTiId:     wenTi,
				HuiHeNum:    huiHeNum,
				AktCardId:   uidCardList[uidIndex].CTId,
				AktedCardId: atkedUserCardList[atkIndex].CTId,
				IsWin:       false,
			}
			uidIndex++
		}
		zhanBao = append(zhanBao, battleMsg)
		huiHeNum++
	}
	var isSuc bool
	if atkIndex > uidIndex || strings.Contains(atkedUser.UID, "test") {
		isSuc = true
	} else {
		isSuc = false
	}
	atkRet := make(map[string]interface{}, 0)
	atkRet["is_suc"] = isSuc
	atkRet["atk_user_neng_li"] = uidCardNengLi
	atkRet["atked_user_neng_li"] = atkedUserNengLi
	atkRet["atk_user_card_list"] = uidCardList
	atkRet["atked_user_card_list"] = atkedUserCardList
	atkRet["zhan_bao"] = zhanBao
	if isSuc {
		if diffPos > 0 {
			atkedInfo.Position = atkedInfo.Position + diffPos
			info.Position = info.Position - diffPos

			if info.Position == 1 {
				//arrBroadcast[fmt.Sprintf("%d", arenaBroadcast.PRI_TOP1)] = 1
				//enAchievements := &EnAchievements{}
				//enAchievements.Notify(user.GetUid(), achievementsDef.ARENA_NO_1, 1)
				//
				//chatTemplate := &ChatTemplate{}
				//chatTemplate.SendArenaTopFailed(user.GetTemplateUserInfo(), atkedUser.GetTemplateUserInfo(), atkRet["server"].(map[string]interface{})["brid"].(int))
			}
			VaOpponents, _ := al.GetOpponentPosition(atkedInfo.Position)
			atkedInfo.VaOpponents = VaOpponents

			//broadcastUpgrade := al.IsBroadcastUpgradeContinue(info["upgrade_continue"].(int), info["upgrade_continue"].(int)+diffPos)
			//if broadcastUpgrade != -1 {
			//	arrBroadcast[fmt.Sprintf("%d", arenaBroadcast.PRI_UPGRADE_CONTINUE)] = broadcastUpgrade
			//}
			info.UpgradeContinue = info.UpgradeContinue + diffPos
			if info.HistoryMinPos > info.Position {
				info.HistoryMinPos = info.Position
			}

			//enAchievements := &EnAchievements{}
			//enAchievements.Notify(user.GetUid(), achievementsDef.ARENA_POSITION_UP, atkedInfo["position"].(int), info["position"].(int))
		}

		if atkedInfo.CurSuc >= MIN_CONTINUE_END {
			//arrBroadcast[fmt.Sprintf("%d", arenaBroadcast.PRI_CONTINUE_END)] = atkedInfo["cur_suc"].(int)
		}
		atkedInfo.CurSuc = 0
		atkedInfo.UpgradeContinue = 0
		VaOpponents, _ := al.GetOpponentPosition(info.Position)
		info.VaOpponents = VaOpponents

		info.CurSuc = info.CurSuc + 1
		if ARR_CONTINUE_SUC[info.CurSuc] > 0 {
			arrBroadcast[fmt.Sprintf("%d", PRI_CONTINUE_SUC)] = info.CurSuc
		}

		if info.CurSuc > info.HistoryMaxSuc {
			info.HistoryMaxSuc = info.CurSuc
			//enAchievements := &EnAchievements{}
			//enAchievements.Notify(user.GetUid(), achievementsDef.ARENA_KEEP_WIN_NUM, info.CurSuc)
		}
	} else {
		info.CurSuc = 0
		info.UpgradeContinue = 0

		atkedInfo.CurSuc = atkedInfo.CurSuc + 1
		if atkedInfo.CurSuc > atkedInfo.HistoryMaxSuc {
			atkedInfo.HistoryMaxSuc = atkedInfo.CurSuc
			//enAchievements := &EnAchievements{}
			//enAchievements.Notify(atkedUser.GetUid(), achievementsDef.ARENA_KEEP_WIN_NUM, atkedInfo["cur_suc"].(int))
		}
		if ARR_CONTINUE_SUC[atkedInfo.CurSuc] > 0 {
			//templateId := al.GetContinueSucTempId(arenaBroadcast.ARR_CONTINUE_SUC[atkedInfo["cur_suc"].(int)])
			//chatTemplate := &ChatTemplate{}
			//message := chatTemplate.MakeMessage(templateId, []interface{}{atkedUser.GetTemplateUserInfo()})
			//al.ArenaBroadcast(message)
		}
	}

	log2.Debug("updateChallenge atk:%v\n, atked:%v", info, atkedInfo)
	//user.Update()

	arenaDao := NewArenaDao()
	err := arenaDao.UpdateChallenge(info, atkedInfo)
	if err != nil {
		return nil, nil, err
	}
	battleDb := BattleMsgList{
		Msg: zhanBao,
	}
	arenaDao.InsertBattleMsg(battleDb)
	return atkRet, arrBroadcast, nil
}
func (al *ArenaLogic) Shop(uid string) []ArenaShopInfo {
	arenaDao := NewArenaDao()
	return arenaDao.GetShopList(uid)
}
func (al *ArenaLogic) BuyItem(uid string, itemId int) (map[string]interface{}, error) {
	arenaDao := NewArenaDao()
	var ret = make(map[string]interface{}, 0)
	shopInfo, err := arenaDao.GetShopInfoByItemId(uid, itemId)
	if err != nil || shopInfo.LingQuTimes <= 0 {
		return ret, fmt.Errorf("没有购买次数")
	}
	_, err = bag.EnUseItem(uid, JJC_Shop_Bi, 100)
	if err != nil {
		return ret, fmt.Errorf("购买失败,使用物品失败，没有足够的货币")
	}
	bagList, err := bag.EnAddItem(uid, itemId, 1)
	if err != nil {
		log2.Error("添加物品失败 用户ID %s 物品id是%d", uid, itemId)
	}
	shopInfo.LingQuTimes = shopInfo.LingQuTimes + 1
	err = arenaDao.UpdateShop(uid, itemId, bson.M{"ling_qu_times": shopInfo.LingQuTimes})
	if err != nil {
		log2.Error("开始52商店修改失败 用湖id %s", uid)
	}
	shopList := arenaDao.GetShopList(uid)
	ret["shop_list"] = shopList
	ret["bag_list"] = bagList
	return ret, nil
}
func (al *ArenaLogic) InitUserShop(uid string) {
	dao := NewArenaDao()
	for i := 0; i < SHOP_MAX; i++ {
		var shop = ArenaShopInfo{UserId: uid, LingQuTimes: Buy_times, ItemId: i}
		dao.InsertShop(uid, shop)
	}
}
